# coding:utf-8

import datetime

from sqlalchemy.orm.exc import NoResultFound

from models import Comment, LoginInfo, Sharer
from core import BaseHandler


class IndexHandler(BaseHandler):
	def get(self):
		# comments = self.application.db.query("select * from note_comment") # torndb方式
		query = self.session.query(Comment)  # 获取整个Comment的list类型
		comments = query.all()
		query2 = self.session.query(Comment.sharer_id)
		tests = query2.all()
		self.render(
			"index.html",
			comments=comments,
			tests=tests
		)


class LoginViewHandler(BaseHandler):
	def get(self):
		self.render("login.html")


class LoginHandler(BaseHandler):
	def post(self):
		email = self.get_argument("email")
		password = self.get_argument("password")
		query = self.session.query(LoginInfo)
		try:
			logininfo = query.filter(LoginInfo.sharer_email == email, LoginInfo.login_password == password).one()
			query_sharer = self.session.query(Sharer)
			sharer = query_sharer.get(logininfo.sharer_id)
			self.set_secure_cookie("sharer",sharer.nickname)
			self.redirect(
				"/"
			)
		except NoResultFound:
			self.redirect()


class SignupViewHandler(BaseHandler):
	def get(self):
		self.render("signup.html")


class SignupHandler(BaseHandler):
	def post(self):
		session = self.session
		nickname = self.get_argument("nickname")
		email = self.get_argument("email")
		password = self.get_argument("password")
		query = session.query(LoginInfo)
		try:
			logininfo = query.filter(LoginInfo.sharer_email == email, LoginInfo.login_password == password).one()
			self.redirect(
				"/signup"
			)
		except NoResultFound:
			sharer = Sharer(nickname=nickname)
			session.add(sharer)
			session.commit()
			logininfo = LoginInfo(sharer_id=sharer.sharer_id, sharer_email=email, login_password=password,
								  register_time=datetime.datetime.now())
			session.add(logininfo)
			session.commit()
			self.set_secure_cookie("sharer",sharer.nickname)